package com.colin.project.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.colin.project.bean.HeadImg;
import com.colin.project.bean.User;
import com.colin.project.bean.Video;
import com.colin.project.jedis.FileJedisOperate;
import com.colin.project.mapper.FileMapper;
import com.colin.project.mapper.UserMapper;
import com.colin.project.service.FileService;
import com.colin.project.util.response.ResponseResult;
import com.colin.project.util.response.Status;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import redis.clients.jedis.JedisPool;

import javax.servlet.http.HttpSession;
import java.util.List;

@Service
public class FileServiceImpl implements FileService {

    @Autowired
    private JedisPool jedisPool;
    @Autowired
    private ResponseResult<String> responseResult;
    @Autowired
    private FileMapper fileMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private FileJedisOperate fileJedisOperate;

    /**
     * 检查缓存的md5值是否存在
     * @param md5
     * @param session
     * @return 如果存在 返回相应文件信息 如果不存在 返回一个结果
     */
    @Override
    @Transactional
    public ResponseResult<String> checkFileMd5(String md5, Integer flag, HttpSession session) {
        int fileId = fileJedisOperate.getFileId(md5);
        if (fileId == 0) {
            responseResult.setStatus(Status.FILE_NOT_EXISTS);
            responseResult.setMessage("文件可以上传");
            return responseResult;
        }
        if(flag == 0){// flag == 0执行头像上传业务
            HeadImg headImg = fileMapper.selectHeadImgById(fileId);

            User loginUser = (User) session.getAttribute("loginUser");
            //1.修改user表中的头像
            userMapper.updateHeadImgById(loginUser.getId(), headImg.getMappingPath());
            //2.修改session中头像
            loginUser.setHeadImg(headImg.getMappingPath());
            session.setAttribute("loginUser", loginUser);
            responseResult.setStatus(Status.FILE_EXISTS);
            responseResult.setMessage("文件已经存在，返回服务端文件信息");
            responseResult.setData(JSONObject.toJSONString(headImg));
        } else {// flag == 1执行视频上传业务
            Video video = fileMapper.selectVideoById(fileId);
            responseResult.setStatus(Status.FILE_EXISTS);
            responseResult.setMessage("文件已经存在，返回服务端文件信息");
            responseResult.setData(JSONObject.toJSONString(video));
        }

        return responseResult;
    }

    public String findVideo(int fileId){
        Video video = fileMapper.selectVideoById(fileId);

        return video.getMappingPath();
    }

    public List<Video> findVideoRecord(){
        return fileMapper.selectVideoRecord();
    }
}
